package me.zhengjie.modules.quartz.task.pull;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.domain.SwitchConfig;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.dto.CityCompanyDto;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.quartz.service.dto.SyncCommon;
import me.zhengjie.modules.quartz.task.dto.PullDataParamDto;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public abstract class PullTaskBase {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MongoTemplate mongoTemplate;

    private String taskName;

    private boolean v20Flag;

    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    public void setV20Flag(boolean v20Flag) {
        this.v20Flag = v20Flag;
    }

    //集团
    @Autowired
    private CorporationService corporationService;
    //城市公司
    @Autowired
    private CityCompanyService cityCompanyService;

    public void corporationPullTask(String jsonParam) {
        Date dynamicDate = null;
        PullDataParamDto paramDto = JSON.parseObject(jsonParam, PullDataParamDto.class);
        if (paramDto != null && StringUtils.isNotBlank(paramDto.getDate())) {
            dynamicDate = DateUtil.parse(paramDto.getDate(), "yyyy-MM-dd");
        }

        log.info("corporationPullTask run start, parseObject:{}", JSON.toJSONString(paramDto));
        String taskKey = RedisKeyUtil.getTaskKey(taskName);
        if (redisUtils.hasKey(taskKey)){
            return;
        }
        redisUtils.set(taskKey, "", 2, TimeUnit.HOURS);

        log.info(taskName + "---开始执行");
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("deleted").is(false), Criteria.where("v20Flag").is(v20Flag));

        if (paramDto != null && StringUtils.isNotBlank(paramDto.getCorporationCode())) {
            criteria.and("corporationCode").is(paramDto.getCorporationCode());
        }
        Query queryCriteria = new Query();
        queryCriteria.addCriteria(criteria);

        List<Corporation> list = mongoTemplate.find(queryCriteria, Corporation.class);
        Date finalDynamicDate = dynamicDate;
        list.forEach(item->{
            if ("SignContactPullTask".equals(taskName)) {
                SwitchConfig switchConfig = item.getSwitchConfig();
                if (switchConfig == null || switchConfig.getEDeals() == null || "关闭".equals(switchConfig.getEDeals())){
                    return;
                }
            }
            List<CityCompanyDto> cityCompanyDtoList= cityCompanyService.getCompanyList(item.getCorporationCode());
            if(null==cityCompanyDtoList)return;
            cityCompanyDtoList.stream().forEach(cityCompanyDto -> {
                if(cityCompanyDto.getStatus() == 1){
                    pullCityCompany(item, cityCompanyDto, finalDynamicDate);
                }
            });
        });

        log.info(taskName + "---执行完毕");
        redisUtils.del(taskKey);

    }

    private void pullCityCompany(Corporation item,CityCompanyDto cityCompanyDto, Date dynamicDate){
        try {
            SyncCommon syncCommon=new SyncCommon();
            syncCommon.setCorporationCode(item.getCorporationCode());
            syncCommon.setAppId(item.getPullAppId());
            syncCommon.setAppKey(item.getPullAppKey());
            syncCommon.setDomain(item.getPullDomain());
            //具体公司信息
            syncCommon.setCityCode(cityCompanyDto.getCityCode());
            syncCommon.setCompanyUuid(cityCompanyDto.getCompanyUuid());
            //是否初始化
            syncCommon.setInit(cityCompanyDto.getInitFlag());
            syncCommon.setV20Flag(item.getV20Flag());
            pull(syncCommon, dynamicDate);
        } catch (Exception e) {
            redisUtils.del(RedisKeyUtil.getTaskKey(taskName));
            log.error("pullCityCompany error {}",e);
        }
    }

    protected abstract void pull(SyncCommon syncCommon, Date dynamicDate);
}
